package com.neo.office.server.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neo.office.server.config.data.Result;
import com.neo.office.server.config.jwt.JwtTokenUtil;
import com.neo.office.server.domain.entity.User;
import com.neo.office.server.domain.entity.UserRole;
import com.neo.office.server.mapper.UserMapper;
import com.neo.office.server.mapper.UserRoleMapper;
import com.neo.office.server.service.UserService;
import com.neo.office.server.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${token.tokenHead}")
    private String tokenHead;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;


    @Override
    public Result login(String username, String password, String code, HttpServletRequest request) {
        String kaptcha = (String) request.getSession().getAttribute("captcha");
        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(kaptcha) || !kaptcha.equalsIgnoreCase(code)){
            return Result.error("验证码错误，请重新输入");
        }
        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())) {
            return Result.error("用户名或密码不正确");
        }
        if (!userDetails.isEnabled()) {
            return Result.error("对不起，你的账号已被停用");
        }
        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //生成token
        String token = jwtTokenUtil.createToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);

        return Result.success("登录成功", tokenMap);
    }

    /**
     * 根据用户名查询用户信息
     *
     * @param username
     * @return
     */
    @Override
    public User getUserByUserName(String username) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
    }

    /**
     * 获取所有用户
     * @param keywords
     * @return
     */
    @Override
    public List<User> getAllUser(String keywords) {
        return userMapper.getAllUser(UserUtils.getCurrentUser().getId(),keywords);
    }

    /**
     * 更新用户角色
     * @param userId
     * @param rids
     * @return
     */
    @Override
    public Result updateUserRole(Integer userId, Integer[] rids) {
        userRoleMapper.delete(new QueryWrapper<UserRole>().eq("userId",userId));
        Integer result = userRoleMapper.addUserRole(userId,rids);
        if (rids.length == result){
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }

    /**
     * 更新用户密码
     * @param oldPass
     * @param pass
     * @param userId
     * @return
     */
    @Override
    public Result updateUserPassword(String oldPass, String pass, Integer userId) {
        User user = userMapper.selectById(userId);
        System.out.println();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //判断旧密码是否正确
        if (encoder.matches(oldPass,user.getPassword())){
            user.setPassword(encoder.encode(pass));
            int code = userMapper.updateById(user);
            if (code == 1){
                return Result.success("更新成功");
            }
            return Result.error("更新失败");
        }
        return null;
    }


}
